#include "ice_agent.h"

#include <rtc_base/logging.h>

#include <algorithm>


namespace xrtc {

// XRTC TODO    
bool IceAgent::create_channel(EventLoop *el, const std::string &transport_name, 
                IceCandidateComponent component) {

    if (getChannel(transport_name, component) != nullptr) {
        return true;
    }  
    
    auto channel = new IceTransportChannel(el, m_allocator, transport_name, component);
    // 连接信号槽，处理ICE 候选地址收集完成后的信号
    channel->signal_candidate_allocate_done.connect(this, &IceAgent::on_candidate_allocate_done);
    m_channels.push_back(channel);

    return true;
}

IceTransportChannel *IceAgent::getChannel(const std::string &transport_name, 
                            IceCandidateComponent component) {

    auto it = _getChannel(transport_name, component);
    return it != m_channels.end()? *it : nullptr;
}

void IceAgent::set_ice_parameters(const std::string &transport_name, IceCandidateComponent component, 
                                  const IceParameters &ice_param) {
    auto channel = getChannel(transport_name, component);
    if (channel) {
        channel->setIceParameters(ice_param);
    }
}

void IceAgent::set_remote_ice_params(const std::string& transport_name, IceCandidateComponent component,
                           const IceParameters& ice_params) {
    auto channel = getChannel(transport_name, component);
    if (channel) {
        channel->set_remote_ice_params(ice_params);
    }
}

void IceAgent::gathering_candidate() {
    for (auto channel : m_channels) {
        channel->gathering_candidate();
    }
}

std::vector<IceTransportChannel *>::iterator IceAgent::_getChannel(const std::string &transport_name, 
        IceCandidateComponent component) {


    return std::find_if(m_channels.begin(), m_channels.end(), 
        [transport_name, component](IceTransportChannel *channel) {
            return channel->getTransportName() == transport_name && channel->getComponent() == component;
    });
}

void IceAgent::on_candidate_allocate_done(IceTransportChannel* channel,
            const std::vector<Candidate>& candidates)
{
    // 将信号发送给上层（transport_controller），通知候选地址收集完成
    signal_candidate_allocate_done(this, channel->getTransportName(),
            channel->getComponent(), candidates);
}
 
}